package cn.iocoder.yudao.module.project.controller.admin.kisbatchcode;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.iocoder.yudao.module.project.dal.dataobject.kismaterialreceipt.KisMaterialReceiptDO;
import cn.iocoder.yudao.module.project.dal.dataobject.supplier.SupplierDO;
import cn.iocoder.yudao.module.project.dal.mysql.kismaterialreceipt.KisMaterialReceiptMapper;
import cn.iocoder.yudao.module.project.dal.mysql.supplier.SupplierMapper;
import com.alibaba.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.project.controller.admin.kisbatchcode.vo.*;
import cn.iocoder.yudao.module.project.dal.dataobject.kisbatchcode.KisBatchCodeDO;
import cn.iocoder.yudao.module.project.service.kisbatchcode.KisBatchCodeService;

@Tag(name = "管理后台 - 箱码")
@RestController
@RequestMapping("/project/kis-batch-code")
@Validated
@Slf4j
public class KisBatchCodeController {

    @Resource
    private KisBatchCodeService kisBatchCodeService;

    @Resource
    private SupplierMapper supplierMapper;

    @Resource
    private KisMaterialReceiptMapper kisMaterialReceiptMapper;

    @PostMapping("/create")
    @Operation(summary = "创建箱码")
    // @PreAuthorize("@ss.hasPermission('project:kis-batch-code:create')")
    public CommonResult<String> createKisBatchCode(@Valid @RequestBody KisBatchCodeSaveReqVO createReqVO) {
        return success(kisBatchCodeService.createKisBatchCode(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新箱码")
    // @PreAuthorize("@ss.hasPermission('project:kis-batch-code:update')")
    public CommonResult<Boolean> updateKisBatchCode(@Valid @RequestBody KisBatchCodeSaveReqVO updateReqVO) {
        kisBatchCodeService.updateKisBatchCode(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除箱码")
    @Parameter(name = "id", description = "编号", required = true)
    // @PreAuthorize("@ss.hasPermission('project:kis-batch-code:delete')")
    public CommonResult<Boolean> deleteKisBatchCode(@RequestParam("id") String id) {
        kisBatchCodeService.deleteKisBatchCode(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得箱码")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    // @PreAuthorize("@ss.hasPermission('project:kis-batch-code:query')")
    public CommonResult<KisBatchCodeRespVO> getKisBatchCode(@RequestParam("id") String id) {
        KisBatchCodeDO kisBatchCode = kisBatchCodeService.getKisBatchCode(id);
        return success(BeanUtils.toBean(kisBatchCode, KisBatchCodeRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得箱码分页")
    // @PreAuthorize("@ss.hasPermission('project:kis-batch-code:query')")
    public CommonResult<PageResult<KisBatchCodeRespVO>> getKisBatchCodePage(@Valid KisBatchCodePageReqVO pageReqVO) {
        PageResult<KisBatchCodeDO> pageResult = kisBatchCodeService.getKisBatchCodePage(pageReqVO);
        PageResult<KisBatchCodeRespVO> result = BeanUtils.toBean(pageResult, KisBatchCodeRespVO.class);
        if (null != result) {
            List<KisBatchCodeRespVO> list = result.getList();
            if (CollectionUtil.isNotEmpty(list)) {
                for (KisBatchCodeRespVO kisBatchCodeRespVO : list) {
                    String supplierId = kisBatchCodeRespVO.getSupplierId();
                    SupplierDO supplierDO = supplierMapper.selectOne(SupplierDO::getId, supplierId);
                    if (null != supplierDO) {
                        String name = supplierDO.getName();
                        kisBatchCodeRespVO.setSupplierName(name);
                    }
                }
            }
        }
        return success(result);
    }

    // @GetMapping("/export-excel")
    // @Operation(summary = "导出箱码 Excel")
    // // @PreAuthorize("@ss.hasPermission('project:kis-batch-code:export')")
    // @ApiAccessLog(operateType = EXPORT)
    // public void exportKisBatchCodeExcel(@Valid KisBatchCodePageReqVO pageReqVO,
    //           HttpServletResponse response) throws IOException {
    //     pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
    //     List<KisBatchCodeDO> list = kisBatchCodeService.getKisBatchCodePage(pageReqVO).getList();
    //     // 导出 Excel
    //     ExcelUtils.write(response, "箱码.xls", "数据", KisBatchCodeRespVO.class,
    //                     BeanUtils.toBean(list, KisBatchCodeRespVO.class));
    // }




    @GetMapping("/exportExcel")
    @Operation(summary = "导出箱码 Excel")
    @ApiAccessLog(operateType = EXPORT)
    public void exportKisBatchCodeExcel(@Valid KisBatchCodePageReqVO pageReqVO,
                                        HttpServletResponse response) throws IOException {
        ExcelWriter excelWriter = null;
        String errorMsg = "导出箱码错误：";
        String fileName =  "箱码" + ".xlsx";
        InputStream inputStream = null;

        try {
            ClassPathResource classPathResource = new ClassPathResource("/template/箱码导出模板.xlsx");
            inputStream = classPathResource.getInputStream();
            Workbook excel = WorkbookFactory.create(inputStream);

            // pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
            // List<KisBatchCodeDO> kisBatchCodeDOS = kisBatchCodeService.getKisBatchCodePage(pageReqVO).getList();
            // List<KisBatchCodeRespVO> datas = BeanUtils.toBean(kisBatchCodeDOS, KisBatchCodeRespVO.class);
            //
            // // 格式化物料名称
            // if (null != datas && datas.size() > 0) {
            //     List<String> materialCodes = datas.stream()
            //             .filter(c -> null != c.getMaterialCode())
            //             .map(c -> c.getMaterialCode())
            //             .distinct()
            //             .collect(Collectors.toList());
            //
            //     QueryWrapper<KisMaterialReceiptDO> queryWrapper = new QueryWrapper<>();
            //     queryWrapper.in("material_code", materialCodes);
            //     List<KisMaterialReceiptDO> kisMaterialReceiptDOS = kisMaterialReceiptMapper.selectList(queryWrapper);
            //     if (CollectionUtil.isNotEmpty(kisMaterialReceiptDOS)) {
            //         for (KisMaterialReceiptDO kisMaterialReceiptDO : kisMaterialReceiptDOS) {
            //             for (KisBatchCodeRespVO data : datas) {
            //                 if (StringUtils.equals(kisMaterialReceiptDO.getMaterialCode(), data.getMaterialCode())) {
            //                     data.setMaterialName(kisMaterialReceiptDO.getMaterialName());
            //                 }
            //             }
            //         }
            //     }
            //
            // }
            //
            // // 格式化供应商
            // List<SupplierDO> supplierDOS = supplierMapper.selectList();
            // if (null != datas && datas.size() > 0) {
            //     for (SupplierDO supplierDO : supplierDOS) {
            //         String name = supplierDO.getName();
            //         String supplierId = supplierDO.getId();
            //
            //         for (KisBatchCodeRespVO data : datas) {
            //             if (StringUtils.equals(data.getSupplierId(), supplierId)) {
            //                 data.setSupplierName(name);
            //             }
            //         }
            //     }
            // }

            List<KisBatchCodeRespVO> datas = this.getKisBatchCodeList(pageReqVO);

            //读取第一个工作表
            Sheet sheet = excel.getSheetAt(0);

            // rowNumber=1表示从第2行开始
            int rowNumber = 1;

            if (null != datas && datas.size() > 0) {
                Row row = sheet.getRow(rowNumber);

                // 创建一个单元格样式，用于设置边框
                CellStyle style = excel.createCellStyle();
                // 设置边框
                style.setBorderTop(BorderStyle.THIN); // 顶部边框
                style.setBorderBottom(BorderStyle.THIN); // 底部边框
                style.setBorderLeft(BorderStyle.THIN); // 左边边框
                style.setBorderRight(BorderStyle.THIN); // 右边边框
                // 设置水平对齐方式
                style.setAlignment(HorizontalAlignment.CENTER);
                // 设置垂直对齐方式
                style.setVerticalAlignment(VerticalAlignment.CENTER);
                style.setWrapText(true); // 设置单元格内容自动换行

                // 先在第2行插入空白行,行数根据datas的大小来确定
                for (KisBatchCodeRespVO data : datas) {
                    Row oldRow = sheet.getRow(rowNumber);
                    sheet.shiftRows(rowNumber, sheet.getLastRowNum(), 1);

                    Row newRow = sheet.createRow(rowNumber);
                    if (oldRow != null) {
                        for (int i = 0; i < oldRow.getLastCellNum(); i++) {
                            Cell oldCell = oldRow.getCell(i);
                            Cell newCell = newRow.createCell(i);
                            if (oldCell != null) {
                                newCell.setCellStyle(oldCell.getCellStyle());
                                switch (oldCell.getCellType()) {
                                    case STRING:
                                        newCell.setCellValue(oldCell.getStringCellValue());
                                        break;
                                    case NUMERIC:
                                        newCell.setCellValue(oldCell.getNumericCellValue());
                                        break;
                                    case BOOLEAN:
                                        newCell.setCellValue(oldCell.getBooleanCellValue());
                                        break;
                                    // ... handle other cell types ...
                                }
                            }
                        }
                    }

                    rowNumber++;
                }

                int newRowNumber = 1;
                for (KisBatchCodeRespVO data : datas) {
                    String id = data.getId();
                    String materialCode = data.getMaterialCode();
                    String materialName = data.getMaterialName();
                    String supplierId = data.getSupplierId();
                    String supplierName = data.getSupplierName();
                    String batchCode = data.getBatchCode();

                    row = sheet.getRow(newRowNumber++);

                    if (null != id) {
                        Cell cell = row.createCell(0);
                        cell.setCellValue(id);
                        cell.setCellStyle(style);
                    }
                    if (null != materialCode) {
                        Cell cell = row.createCell(1);
                        cell.setCellValue(materialCode);
                        cell.setCellStyle(style);
                    }
                    if (null != materialName) {
                        Cell cell = row.createCell(2);
                        cell.setCellValue(materialName);
                        cell.setCellStyle(style);
                    }
                    if (null != supplierId) {
                        Cell cell = row.createCell(3);
                        cell.setCellValue(supplierId);
                        cell.setCellStyle(style);
                    }
                    if (null != supplierName) {
                        Cell cell = row.createCell(4);
                        cell.setCellValue(supplierName);
                        cell.setCellStyle(style);
                    }
                    if (null != batchCode) {
                        Cell cell = row.createCell(5);
                        cell.setCellValue(batchCode);
                        cell.setCellStyle(style);
                    }
                }
            }

           //使用输出流进行表格下载,基于浏览器作为客户端下载
           OutputStream out = response.getOutputStream();
           response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
           response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));;//指定以附件形式进行下载
           excel.write(out);
           out.flush();
           out.close();
           excel.close();
        }
        catch (Exception e) {
            log.error(errorMsg, e);
        } finally {
            IoUtil.close(excelWriter);
        }
    }

    @GetMapping("/list")
    @Operation(summary = "获得箱码不分页")
    public CommonResult<PageResult<KisBatchCodeRespVO>> list(@Valid KisBatchCodePageReqVO pageReqVO) {
        List<KisBatchCodeRespVO> kisBatchCodeList = this.getKisBatchCodeList(pageReqVO);
        PageResult result = new PageResult();
        result.setList(kisBatchCodeList);
        result.setTotal((long) kisBatchCodeList.size());
        return success(result);
    }

    private List<KisBatchCodeRespVO> getKisBatchCodeList(KisBatchCodePageReqVO pageReqVO) {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<KisBatchCodeDO> kisBatchCodeDOS = kisBatchCodeService.getKisBatchCodePage(pageReqVO).getList();
        List<KisBatchCodeRespVO> datas = BeanUtils.toBean(kisBatchCodeDOS, KisBatchCodeRespVO.class);

        // 格式化物料名称
        if (null != datas && datas.size() > 0) {
            List<String> materialCodes = datas.stream()
                    .filter(c -> null != c.getMaterialCode())
                    .map(c -> c.getMaterialCode())
                    .distinct()
                    .collect(Collectors.toList());

            QueryWrapper<KisMaterialReceiptDO> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("material_code", materialCodes);
            List<KisMaterialReceiptDO> kisMaterialReceiptDOS = kisMaterialReceiptMapper.selectList(queryWrapper);
            if (CollectionUtil.isNotEmpty(kisMaterialReceiptDOS)) {
                for (KisMaterialReceiptDO kisMaterialReceiptDO : kisMaterialReceiptDOS) {
                    for (KisBatchCodeRespVO data : datas) {
                        if (StringUtils.equals(kisMaterialReceiptDO.getMaterialCode(), data.getMaterialCode())) {
                            data.setMaterialName(kisMaterialReceiptDO.getMaterialName());
                        }
                    }
                }
            }

        }

        // 格式化供应商
        List<SupplierDO> supplierDOS = supplierMapper.selectList();
        if (null != datas && datas.size() > 0) {
            for (SupplierDO supplierDO : supplierDOS) {
                String name = supplierDO.getName();
                String supplierId = supplierDO.getId();

                for (KisBatchCodeRespVO data : datas) {
                    if (StringUtils.equals(data.getSupplierId(), supplierId)) {
                        data.setSupplierName(name);
                    }
                }
            }
        }

        return datas;
    }

}